<template>
  <div class="login-container">
    <div class="left">
      <div class="title-box">
        <img src="@/assets/img/login_icon.png" alt="" />
        <span class="title">黑马面面</span>
        <span class="line"></span>
        <span class="sub-title">用户登录</span>
      </div>
      <!--
        el-for的属性
          model: 绑定的模型值，也是将来要提交给后台服务器的值
          rules：校验的规则写在它里面
          ref：获取整个表单dom节点
          label-width：文字宽度
       -->
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        class="login-form"
      >
        <!--
          el-form-item的属性
          prop校验规则字段，和rules中要保持一致
        -->
        <el-form-item prop="phone">
          <el-input
            prefix-icon="el-icon-user"
            v-model="loginForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item prop="password">
          <!--
            prefix-icon: 前置图标
            show-password：显示密码
           -->
          <el-input
            prefix-icon="el-icon-lock"
            v-model="loginForm.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="17">
            <el-form-item prop="code">
              <el-input
                prefix-icon="el-icon-key"
                v-model="loginForm.code"
                placeholder="请输入验证码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left:10px;">
            <img
              :src="loginCaptchaUrl"
              @click="changeLoginCaptchaUrl"
              alt=""
              class="captcha"
            />
          </el-col>
        </el-row>
        <el-form-item prop="isChecked">
          <el-checkbox v-model="isChecked"></el-checkbox>
          我已阅读并同意<el-link
            type="primary"
            :underline="false"
            href="http://itheima.com"
            target="_blank"
            >用户协议</el-link
          >和<el-link
            type="primary"
            :underline="false"
            href="http://itheima.com"
            target="_blank"
            >隐私条款</el-link
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%" @click="login"
            >登 录</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%" @click="register"
            >注 册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="right">
      <img src="@/assets/img/login_bg.png" alt="" />
    </div>
    <!-- 这里设置ref的目的是为了在父组件(Login.vue)中拿到子组件(Register.vue)的实例 -->
    <register ref="registerRef" />
  </div>
</template>

<script>
// 按需导入
import { saveToken } from '@/utils/token'
import Register from './Register'
export default {
  components: {
    Register
  },
  data () {
    return {
      // 需要提交给服务器的登录时候的参数
      loginForm: {
        phone: '18511111111', // 手机号
        password: '12345678', // 密码
        code: '' // 验证码
      },
      isChecked: false, // 是否勾选
      loginCaptchaUrl: process.env.VUE_APP_BASEURL + 'captcha?type=login', // 验证码地址
      // 规则
      rules: {
        phone: [
          {
            validator: (rule, value, callback) => {
              /**
               * rule：规则
               * value：用户输入的值
               * callback：决定是否校验ok，如果里面没有接 new Error('xxxx')，callback必须调用
               */
              if (!value) {
                // return 阻止代码继续往下执行
                return callback(new Error('手机号不能为空!'))
              }

              const reg = /^1[3456789][0-9]{9}$/
              if (!reg.test(value)) {
                // return 阻止代码继续往下执行
                return callback(new Error('手机号不合法!'))
              }

              // 校验ok
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
        isChecked: [
          {
            validator: (rule, value, callback) => {
              if (!this.isChecked) {
                return callback(new Error('必须勾选用户协议'))
              }

              callback()
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // 更改图形验证码的地址
    changeLoginCaptchaUrl () {
      this.loginCaptchaUrl = `${
        process.env.VUE_APP_BASEURL
      }captcha?type=login&t=${new Date() - 0}`
    },
    // 登录
    login () {
      // 对整个表单提交之前做最后一次校验
      // async要加在离 await 最近的函数上面
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return

        const res = await this.$http.post('login', this.loginForm)

        if (res.code === 200) {
          // 保存token
          saveToken(res.data.token)
          // 提示
          this.$message({
            message: '登录成功~',
            type: 'success'
          })
          // 跳转
          this.$router.push('/layout')
        } else {
          this.$message.error(res.message)
          this.changeLoginCaptchaUrl()
        }
      })
    },
    // 注册
    register () {
      // console.log(this.$refs.registerRef)
      this.$refs.registerRef.dialogVisible = true
    }
  }
}
</script>

<style lang="less">
.login-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background: linear-gradient(225deg, #1493fa, #01c6fa);
  .left {
    width: 478px;
    height: 550px;
    background: #f5f5f5;
    padding: 48px;
    .title-box {
      display: flex;
      align-items: center;
      img {
        width: 22px;
        height: 17px;
        margin-right: 16px;
      }
      .title {
        font-size: 24px;
        margin-right: 14px;
      }
      .line {
        width: 1px;
        background-color: #c7c7c7;
        height: 27px;
        margin-right: 12px;
      }
      .sub-title {
        font-size: 22px;
      }
    }
    .login-form {
      margin-top: 20px;
      .captcha {
        width: 100%;
        height: 40px;
      }
    }
  }
}
</style>
